//
//  NSStringUtils.m
//  Communique
//
//  Created by Thomas on 19/03/2009.
//  Copyright 2009 Delete Ltd. All rights reserved.
//

#import "NSStringUtils.h"

@implementation NSStringUtils

+ (NSMutableString *) replaceString:(NSString *)sourceString from:(NSString *)oldSubstring to:(NSString *)newSubstring
{
    unsigned int     len;
    NSMutableString *mstr;
    NSRange          searchRange;
    NSRange          resultRange;
    
#define	ADDON_SPACE 10
    
    searchRange.location = 0;
    searchRange.length = len = [sourceString length];
    mstr = [NSMutableString stringWithCapacity:(len + ADDON_SPACE)];
    NSParameterAssert(mstr != nil);
    
    for (;;)
    {
        resultRange = [sourceString rangeOfString:oldSubstring options:NSLiteralSearch range:searchRange];
        if (resultRange.length == 0)
            break;	// Not found!
        
        // append and replace
        [mstr appendString:[sourceString substringWithRange:
							NSMakeRange(searchRange.location, resultRange.location - searchRange.location)] ];
        [mstr appendString:newSubstring];
        
        // update search Range
        searchRange.location = resultRange.location + resultRange.length;
        searchRange.length   = len - searchRange.location;
        
        //	NSLog(@"resultRange.location=%d\n", resultRange.location);
        //	NSLog(@"resultRange.length=%d\n", resultRange.length);
    }
    
    [mstr appendString:[sourceString substringWithRange:searchRange]];
    
    return mstr;
}

@end
